package top.mypath.service;

import top.mypath.model.dto.CacheData;
import top.mypath.model.dto.CheckBoxItem;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.util.List;
import java.util.Optional;

/**
 * @author LiYalin
 */
public class JCheckBoxChangeListener implements ChangeListener {

    @Override
    public void stateChanged(ChangeEvent e) {
        List<CheckBoxItem> selectedCheckBoxItems = CacheData.getSelectedCheckBoxItems();
        JCheckBox source = (JCheckBox) e.getSource();
        String text = source.getText();
        Optional<CheckBoxItem> first = selectedCheckBoxItems.stream().filter(item -> text.equals(item.getCellName())).findFirst();
        if(source.isSelected()){
            if(!first.isPresent()){
                selectedCheckBoxItems.add(CacheData.getShowCheckBoxItemMap().get(text));
            }
        }else{
            if(first.isPresent()){
                selectedCheckBoxItems.remove(CacheData.getShowCheckBoxItemMap().get(text));
            }
        }
    }
}
